package com.JudgeOnline.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyFilter extends HttpServlet implements Filter {

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {

		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpSession session = request.getSession(true);
		String login = (String) session.getAttribute("login");
		String url = request.getRequestURI();

		if (login == null || login.equals("")) {
			if (url != null && !url.equals("")
					&& (url.indexOf("login") < 0 && url.indexOf("index") < 0)) {
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();

				response.setHeader("refresh", "2;URL=index.jsp");
				out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
				out.println("<HTML>");
				out.println("  <HEAD><TITLE>未登录！</TITLE></HEAD>");
				out.println("  <BODY>");
				out.println("请先登录！2秒以后跳转到<a href='index.jsp'>登录页面</a>");
				out.println("  </BODY>");
				out.println("</HTML>");
				out.flush();
				out.close();
				return;
			}
		}
		arg2.doFilter(arg0, arg1);
		return;
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
}